package com.wanshu.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wanshu.common.annotation.SystemLog;
import com.wanshu.common.util.PageUtils;
import com.wanshu.sys.entity.SysRole;
import com.wanshu.sys.mapper.SysRoleMapper;
import com.wanshu.sys.model.SysRoleQueryDTO;
import com.wanshu.sys.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author 波哥
 * @since 2024-05-28
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public PageUtils queryPage(SysRoleQueryDTO queryDTO) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<SysRole>().like(
                StringUtils.isNotEmpty(queryDTO.getRoleName()), "role_name", queryDTO.getRoleName()
        ).eq("is_delete", 0);
        Page<SysRole> page = this.page(queryDTO.page(), wrapper);
        return new PageUtils(page);
    }

    @SystemLog("添加角色")
    @Override
    public void saveRole(SysRole sysRole) {
        save(sysRole);
    }

    @SystemLog("更新角色")
    @Override
    public void updateRole(SysRole sysRole) {
        QueryWrapper<SysRole> queryWrapper =
                new QueryWrapper<SysRole>().eq("role_Id", sysRole.getRoleId());
        update(sysRole, queryWrapper);
    }

    @SystemLog("添加或更新角色")
    @Override
    public void saveOrUpdateRole(SysRole sysRole) {
        if(sysRole.getRoleId() != null){
            updateRole(sysRole);
        }else{
            saveRole(sysRole);
        }
    }

    @Override
    public boolean checkRoleName(String roleName) {
        if(StringUtils.isEmpty(roleName)){
            return false;
        }
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<SysRole>().eq("role_name", roleName);
        int count = this.count(queryWrapper);
        return count > 0;
    }

    @SystemLog("删除角色")
    @Override
    public boolean deleteRole(Long roleId) {
        //先行判断此角色是否分配给了用户, 如果用户或者角色绑定了菜单, 不允许删除角色
        int count = baseMapper.checkRoleCanDelete(roleId);
        boolean result = false;
        if(count == 0){
            QueryWrapper<SysRole> queryWrapper =
                    new QueryWrapper<SysRole>().eq("role_Id", roleId);
            //result = this.remove(queryWrapper);
            SysRole role = baseMapper.selectOne(queryWrapper);
            role.setIsDelete(1);
            result = update(role, queryWrapper);
        }
        return result;
    }

    @Override
    public List<SysRole> queryByUserId(Long userId) {
        return sysRoleMapper.queryByUserId(userId);
    }


}
